function [b,bstd,tb,R2,AR2,error]=olsnw(Y,X,type,nlag)

% Performs linear regression estimation (based on Spatial Econometrix
% Toolbox by James P. LeSage jlesage@spatial-econometrics.com)
%-------------------------------------------------------------------------;
% INPUTS;
% y=dependent variable vector (nobs x 1)
% x=independent variables matrix (nobs x nvar)
% type determines calculation of standard errors:
%   type=0; standard OLS
%   type=1; Newey-West HAC standard errors
% nlag=lag length for Newey-West correction (set to 0 for type 0)
%-------------------------------------------------------------------------;
% OUTPUT:
% b=vector of parameters
% bstd=vector of standard errors for parameters
% tb=vector of t-statistics
% R2=R-squared
% AR2=adjusted R-squared 
% error=regression residuals
%-------------------------------------------------------------------------;

T1=length(Y);
T2=length(X);
if T1~=T2
disp('Sample size is not correct');
end

[nobs,nvar]=size(X);

XX=(X'*X)\eye(nvar);
b=XX*(X'*Y);
error=Y-X*b;

if type==0 %OLS standard errors;
bstd=sqrt(((error'*error)/(nobs-nvar))*(diag(XX)));
end;

if type==1 %Newey-West correction;
    emat=repmat(error',nvar,1); 
    hhat=emat.*X';
    G=zeros(nvar,nvar); 
    w=zeros(2*nlag+1,1);
    a=0;

    while a~=nlag+1
        ga=zeros(nvar,nvar);
        w(nlag+1+a,1)=(nlag+1-a)/(nlag+1);
        za=hhat(:,(a+1):nobs)*hhat(:,1:nobs-a)';
          if a==0
           ga=ga+za;
          else
           ga=ga+za+za';
          end;
        G=G+w(nlag+1+a,1)*ga;
        a=a+1;
    end;
    
    V=XX*G*XX;
    bstd= sqrt(diag(V));
end;

tb=b./bstd;

R2=1.-(error'*error)./((Y-mean(Y))'*(Y-mean(Y)));
AR2=1.-(error'*error)./((Y-mean(Y))'*(Y-mean(Y)))*(nobs-1)/(nobs-nvar);

